package com.columboid.testharness.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

	public static String getMacAddress() {
		String macStr = "";
		try { // InetAddress address = InetAddress.getLocalHost();
			InetAddress address = InetAddress.getLocalHost();
			NetworkInterface ni = NetworkInterface.getByInetAddress(address);
			if (ni != null) {
				byte[] mac = ni.getHardwareAddress();
				if (mac != null) {
					macStr = macbyte2macstr(mac);
				} else {
					System.out
							.println("Address doesn't exist or is not accessible.");
				}
			} else {
				System.out
						.println("Network Interface for the specified address is not found.");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			Log4j.logger.error(e.toString());
		} catch (SocketException e) {
			e.printStackTrace();
			Log4j.logger.error(e.toString());
		}
		// System.out.println(macStr);
		return macStr;
	}

	static String macbyte2macstr(byte[] mac) {
		String macStr = "";
		for (int i = 0; i < mac.length; i++) {
			int a = mac[i] & 0xFF;
			if (a > 15)
				macStr += Integer.toHexString(a);
			else
				macStr += "0" + Integer.toHexString(a);
			if (i < (mac.length - 1)) {
				macStr += "-";
			}
		}
		return macStr;
	}

	public static String getMac() throws java.io.IOException {
		Process p = Runtime.getRuntime().exec("getmac /fo csv /nh");
		java.io.BufferedReader in = new java.io.BufferedReader(
				new java.io.InputStreamReader(p.getInputStream()));
		String line;
		line = in.readLine();
		String[] result = line.split(",");
		return result[0].replace('"', ' ').trim();
	}

}
